* (bug 3475) anon contrib links on Special:Newpages
[lhc/web/wiklou.git] / includes / SpecialUpload.php
1 <?php
2 /**
3 *
4 * @package MediaWiki
5 * @subpackage SpecialPage
6 */
7
8 /**
9 *
10 */
11 require_once 'Image.php';
12 require_once 'MacBinary.php';
13 require_once 'Licenses.php';
14 /**
15 * Entry point
16 */
17 function wfSpecialUpload() {
18 global $wgRequest;
19 $form = new UploadForm( $wgRequest );
20 $form->execute();
21 }
22
23 /**
24 *
25 * @package MediaWiki
26 * @subpackage SpecialPage
27 */
28 class UploadForm {
29 /**#@+
30 * @access private
31 */
32 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
33 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
34 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
35 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile;
36 /**#@-*/
37
38 /**
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
42 */
43 function UploadForm( &$request ) {
44 $this->mDestFile = $request->getText( 'wpDestFile' );
45
46 if( !$request->wasPosted() ) {
47 # GET requests just give the main form; no data except wpDestfile.
48 return;
49 }
50
51 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning');
52 $this->mReUpload = $request->getCheck( 'wpReUpload' );
53 $this->mUpload = $request->getCheck( 'wpUpload' );
54
55 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
56 $this->mLicense = $request->getText( 'wpLicense' );
57 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
58 $this->mUploadSource = $request->getText( 'wpUploadSource');
59
60 $this->mAction = $request->getVal( 'action' );
61
62 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
63 if( !empty( $this->mSessionKey ) &&
64 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
65 /**
66 * Confirming a temporarily stashed upload.
67 * We don't want path names to be forged, so we keep
68 * them in the session on the server and just give
69 * an opaque key to the user agent.
70 */
71 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
72 $this->mUploadTempName = $data['mUploadTempName'];
73 $this->mUploadSize = $data['mUploadSize'];
74 $this->mOname = $data['mOname'];
75 $this->mUploadError = 0/*UPLOAD_ERR_OK*/;
76 $this->mStashed = true;
77 $this->mRemoveTempFile = false;
78 } else {
79 /**
80 *Check for a newly uploaded file.
81 */
82 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
83 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
84 $this->mOname = $request->getFileName( 'wpUploadFile' );
85 $this->mUploadError = $request->getUploadError( 'wpUploadFile' );
86 $this->mSessionKey = false;
87 $this->mStashed = false;
88 $this->mRemoveTempFile = false; // PHP will handle this
89 }
90 }
91
92 /**
93 * Start doing stuff
94 * @access public
95 */
96 function execute() {
97 global $wgUser, $wgOut;
98 global $wgEnableUploads, $wgUploadDirectory;
99
100 /** Show an error message if file upload is disabled */
101 if( ! $wgEnableUploads ) {
102 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
103 return;
104 }
105
106 /** Various rights checks */
107 if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) {
108 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
109 return;
110 }
111 if( wfReadOnly() ) {
112 $wgOut->readOnlyPage();
113 return;
114 }
115
116 /** Check if the image directory is writeable, this is a common mistake */
117 if ( !is_writeable( $wgUploadDirectory ) ) {
118 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
119 return;
120 }
121
122 if( $this->mReUpload ) {
123 $this->unsaveUploadedFile();
124 $this->mainUploadForm();
125 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
126 $this->processUpload();
127 } else {
128 $this->mainUploadForm();
129 }
130
131 $this->cleanupTempFile();
132 }
133
134 /* -------------------------------------------------------------- */
135
136 /**
137 * Really do the upload
138 * Checks are made in SpecialUpload::execute()
139 * @access private
140 */
141 function processUpload() {
142 global $wgUser, $wgOut, $wgLang, $wgContLang;
143 global $wgUploadDirectory;
144 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
145
146 /* Check for PHP error if any, requires php 4.2 or newer */
147 if ( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
148 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
149 return;
150 }
151
152 /**
153 * If there was no filename or a zero size given, give up quick.
154 */
155 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
156 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
157 return;
158 }
159
160 # Chop off any directories in the given filename
161 if ( $this->mDestFile ) {
162 $basename = basename( $this->mDestFile );
163 } else {
164 $basename = basename( $this->mOname );
165 }
166
167 /**
168 * We'll want to blacklist against *any* 'extension', and use
169 * only the final one for the whitelist.
170 */
171 list( $partname, $ext ) = $this->splitExtensions( $basename );
172 if( count( $ext ) ) {
173 $finalExt = $ext[count( $ext ) - 1];
174 } else {
175 $finalExt = '';
176 }
177 $fullExt = implode( '.', $ext );
178
179 if ( strlen( $partname ) < 3 ) {
180 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
181 return;
182 }
183
184 /**
185 * Filter out illegal characters, and try to make a legible name
186 * out of it. We'll strip some silently that Title would die on.
187 */
188 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
189 $nt = Title::newFromText( $filtered );
190 if( is_null( $nt ) ) {
191 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
192 return;
193 }
194 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
195 $this->mUploadSaveName = $nt->getDBkey();
196
197 /**
198 * If the image is protected, non-sysop users won't be able
199 * to modify it by uploading a new revision.
200 */
201 if( !$nt->userCanEdit() ) {
202 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
203 }
204
205 /**
206 * In some cases we may forbid overwriting of existing files.
207 */
208 $overwrite = $this->checkOverwrite( $this->mUploadSaveName );
209 if( WikiError::isError( $overwrite ) ) {
210 return $this->uploadError( $overwrite->toString() );
211 }
212
213 /* Don't allow users to override the blacklist (check file extension) */
214 global $wgStrictFileExtensions;
215 global $wgFileExtensions, $wgFileBlacklist;
216 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
217 ($wgStrictFileExtensions &&
218 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
219 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
220 }
221
222 /**
223 * Look at the contents of the file; if we can recognize the
224 * type but it's corrupt or data of the wrong type, we should
225 * probably not accept it.
226 */
227 if( !$this->mStashed ) {
228 $this->checkMacBinary();
229 $veri = $this->verify( $this->mUploadTempName, $finalExt );
230
231 if( $veri !== true ) { //it's a wiki error...
232 return $this->uploadError( $veri->toString() );
233 }
234 }
235
236 /**
237 * Provide an opportunity for extensions to add futher checks
238 */
239 $error = '';
240 if( !wfRunHooks( 'UploadVerification',
241 array( $this->mUploadSaveName, $this->mUploadTempName, &$error ) ) ) {
242 return $this->uploadError( $error );
243 }
244
245 /**
246 * Check for non-fatal conditions
247 */
248 if ( ! $this->mIgnoreWarning ) {
249 $warning = '';
250
251 global $wgCapitalLinks;
252 if( $wgCapitalLinks ) {
253 $filtered = ucfirst( $filtered );
254 }
255 if( $this->mUploadSaveName != $filtered ) {
256 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
257 }
258
259 global $wgCheckFileExtensions;
260 if ( $wgCheckFileExtensions ) {
261 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
262 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
263 }
264 }
265
266 global $wgUploadSizeWarning;
267 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
268 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
269 # value, perhaps add GB,MB and KB suffixes?
270 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
271 }
272 if ( $this->mUploadSize == 0 ) {
273 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
274 }
275
276 if( $nt->getArticleID() ) {
277 global $wgUser;
278 $sk = $wgUser->getSkin();
279 $dlink = $sk->makeKnownLinkObj( $nt );
280 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
281 }
282
283 if( $warning != '' ) {
284 /**
285 * Stash the file in a temporary location; the user can choose
286 * to let it through and we'll complete the upload then.
287 */
288 return $this->uploadWarning( $warning );
289 }
290 }
291
292 /**
293 * Try actually saving the thing...
294 * It will show an error form on failure.
295 */
296 $hasBeenMunged = !empty( $this->mSessionKey ) || $this->mRemoveTempFile;
297 if( $this->saveUploadedFile( $this->mUploadSaveName,
298 $this->mUploadTempName,
299 $hasBeenMunged ) ) {
300 /**
301 * Update the upload log and create the description page
302 * if it's a new file.
303 */
304 $img = Image::newFromName( $this->mUploadSaveName );
305 $success = $img->recordUpload( $this->mUploadOldVersion,
306 $this->mUploadDescription,
307 $this->mLicense,
308 $this->mUploadCopyStatus,
309 $this->mUploadSource );
310
311 if ( $success ) {
312 $this->showSuccess();
313 } else {
314 // Image::recordUpload() fails if the image went missing, which is
315 // unlikely, hence the lack of a specialised message
316 $wgOut->fileNotFoundError( $this->mUploadSaveName );
317 }
318 }
319 }
320
321 /**
322 * Move the uploaded file from its temporary location to the final
323 * destination. If a previous version of the file exists, move
324 * it into the archive subdirectory.
325 *
326 * @todo If the later save fails, we may have disappeared the original file.
327 *
328 * @param string $saveName
329 * @param string $tempName full path to the temporary file
330 * @param bool $useRename if true, doesn't check that the source file
331 * is a PHP-managed upload temporary
332 */
333 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
334 global $wgUploadDirectory, $wgOut;
335
336 $fname= "SpecialUpload::saveUploadedFile";
337
338 $dest = wfImageDir( $saveName );
339 $archive = wfImageArchiveDir( $saveName );
340 $this->mSavedFile = "{$dest}/{$saveName}";
341
342 if( is_file( $this->mSavedFile ) ) {
343 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
344 wfSuppressWarnings();
345 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
346 wfRestoreWarnings();
347
348 if( ! $success ) {
349 $wgOut->fileRenameError( $this->mSavedFile,
350 "${archive}/{$this->mUploadOldVersion}" );
351 return false;
352 }
353 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
354 }
355 else {
356 $this->mUploadOldVersion = '';
357 }
358
359 wfSuppressWarnings();
360 $success = $useRename
361 ? rename( $tempName, $this->mSavedFile )
362 : move_uploaded_file( $tempName, $this->mSavedFile );
363 wfRestoreWarnings();
364
365 if( ! $success ) {
366 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
367 return false;
368 } else {
369 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
370 }
371
372 chmod( $this->mSavedFile, 0644 );
373 return true;
374 }
375
376 /**
377 * Stash a file in a temporary directory for later processing
378 * after the user has confirmed it.
379 *
380 * If the user doesn't explicitly cancel or accept, these files
381 * can accumulate in the temp directory.
382 *
383 * @param string $saveName - the destination filename
384 * @param string $tempName - the source temporary file to save
385 * @return string - full path the stashed file, or false on failure
386 * @access private
387 */
388 function saveTempUploadedFile( $saveName, $tempName ) {
389 global $wgOut;
390 $archive = wfImageArchiveDir( $saveName, 'temp' );
391 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
392
393 $success = $this->mRemoveTempFile
394 ? rename( $tempName, $stash )
395 : move_uploaded_file( $tempName, $stash );
396 if ( !$success ) {
397 $wgOut->fileCopyError( $tempName, $stash );
398 return false;
399 }
400
401 return $stash;
402 }
403
404 /**
405 * Stash a file in a temporary directory for later processing,
406 * and save the necessary descriptive info into the session.
407 * Returns a key value which will be passed through a form
408 * to pick up the path info on a later invocation.
409 *
410 * @return int
411 * @access private
412 */
413 function stashSession() {
414 $stash = $this->saveTempUploadedFile(
415 $this->mUploadSaveName, $this->mUploadTempName );
416
417 if( !$stash ) {
418 # Couldn't save the file.
419 return false;
420 }
421
422 $key = mt_rand( 0, 0x7fffffff );
423 $_SESSION['wsUploadData'][$key] = array(
424 'mUploadTempName' => $stash,
425 'mUploadSize' => $this->mUploadSize,
426 'mOname' => $this->mOname );
427 return $key;
428 }
429
430 /**
431 * Remove a temporarily kept file stashed by saveTempUploadedFile().
432 * @access private
433 */
434 function unsaveUploadedFile() {
435 global $wgOut;
436 wfSuppressWarnings();
437 $success = unlink( $this->mUploadTempName );
438 wfRestoreWarnings();
439 if ( ! $success ) {
440 $wgOut->fileDeleteError( $this->mUploadTempName );
441 }
442 }
443
444 /* -------------------------------------------------------------- */
445
446 /**
447 * Show some text and linkage on successful upload.
448 * @access private
449 */
450 function showSuccess() {
451 global $wgUser, $wgOut, $wgContLang;
452
453 $sk = $wgUser->getSkin();
454 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
455 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
456 $dlink = $sk->makeKnownLink( $dname, $dname );
457
458 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
459 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
460 $wgOut->addHTML( $text );
461 $wgOut->returnToMain( false );
462 }
463
464 /**
465 * @param string $error as HTML
466 * @access private
467 */
468 function uploadError( $error ) {
469 global $wgOut;
470 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
471 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
472 }
473
474 /**
475 * There's something wrong with this file, not enough to reject it
476 * totally but we require manual intervention to save it for real.
477 * Stash it away, then present a form asking to confirm or cancel.
478 *
479 * @param string $warning as HTML
480 * @access private
481 */
482 function uploadWarning( $warning ) {
483 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
484 global $wgUseCopyrightUpload;
485
486 $this->mSessionKey = $this->stashSession();
487 if( !$this->mSessionKey ) {
488 # Couldn't save file; an error has been displayed so let's go.
489 return;
490 }
491
492 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
493 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
494
495 $save = wfMsgHtml( 'savefile' );
496 $reupload = wfMsgHtml( 'reupload' );
497 $iw = wfMsgWikiHtml( 'ignorewarning' );
498 $reup = wfMsgWikiHtml( 'reuploaddesc' );
499 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
500 $action = $titleObj->escapeLocalURL( 'action=submit' );
501
502 if ( $wgUseCopyrightUpload )
503 {
504 $copyright = "
505 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
506 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
507 ";
508 } else {
509 $copyright = "";
510 }
511
512 $wgOut->addHTML( "
513 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
514 <input type='hidden' name='wpIgnoreWarning' value='1' />
515 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
516 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
517 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
518 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
519 {$copyright}
520 <table border='0'>
521 <tr>
522 <tr>
523 <td align='right'>
524 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
525 </td>
526 <td align='left'>$iw</td>
527 </tr>
528 <tr>
529 <td align='right'>
530 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
531 </td>
532 <td align='left'>$reup</td>
533 </tr>
534 </tr>
535 </table></form>\n" );
536 }
537
538 /**
539 * Displays the main upload form, optionally with a highlighted
540 * error message up at the top.
541 *
542 * @param string $msg as HTML
543 * @access private
544 */
545 function mainUploadForm( $msg='' ) {
546 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
547 global $wgUseCopyrightUpload;
548
549 $cols = intval($wgUser->getOption( 'cols' ));
550 $ew = $wgUser->getOption( 'editwidth' );
551 if ( $ew ) $ew = " style=\"width:100%\"";
552 else $ew = '';
553
554 if ( '' != $msg ) {
555 $sub = wfMsgHtml( 'uploaderror' );
556 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
557 "<span class='error'>{$msg}</span>\n" );
558 }
559 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
560 $sk = $wgUser->getSkin();
561
562
563 $sourcefilename = wfMsgHtml( 'sourcefilename' );
564 $destfilename = wfMsgHtml( 'destfilename' );
565 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
566
567 $licenses = new Licenses();
568 $license = wfMsgHtml( 'license' );
569 $nolicense = wfMsgHtml( 'nolicense' );
570 $licenseshtml = $licenses->getHtml();
571
572 $ulb = wfMsgHtml( 'uploadbtn' );
573
574
575 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
576 $action = $titleObj->escapeLocalURL();
577
578 $encDestFile = htmlspecialchars( $this->mDestFile );
579 $source = null;
580
581 if ( $wgUseCopyrightUpload )
582 {
583 $source = "
584 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
585 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
586 htmlspecialchars($this->mUploadCopyStatus). "\" size='40' /></td>
587 </tr><tr>
588 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
589 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
590 htmlspecialchars($this->mUploadSource). "\" size='40' /></td>
591 " ;
592 }
593
594 $wgOut->addHTML( "
595 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
596 <table border='0'><tr>
597
598 <td align='right'>{$sourcefilename}:</td><td align='left'>
599 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?"":"onchange='fillDestFilename()' ") . "size='40' />
600 </td></tr><tr>
601
602 <td align='right'>{$destfilename}:</td><td align='left'>
603 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
604 </td></tr><tr>
605
606 <td align='right'>{$summary}</td><td align='left'>
607 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
608 . htmlspecialchars( $this->mUploadDescription ) .
609 "</textarea>
610 </td></tr><tr>" );
611
612 if ( $licenseshtml != '' ) {
613 $wgOut->addHTML( "
614 <td align='right'>$license:</td>
615 <td align='left'>
616 <select name='wpLicense'>
617 <option value=''>$nolicense</option>
618 $licenseshtml
619 </select>
620 </td></tr><tr>
621 ");
622 }
623 $wgOut->addHtml( "{$source}
624 </tr>
625 <tr><td></td><td align='left'>
626 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
627 </td></tr></table></form>\n" );
628 }
629
630 /* -------------------------------------------------------------- */
631
632 /**
633 * Split a file into a base name and all dot-delimited 'extensions'
634 * on the end. Some web server configurations will fall back to
635 * earlier pseudo-'extensions' to determine type and execute
636 * scripts, so the blacklist needs to check them all.
637 *
638 * @return array
639 */
640 function splitExtensions( $filename ) {
641 $bits = explode( '.', $filename );
642 $basename = array_shift( $bits );
643 return array( $basename, $bits );
644 }
645
646 /**
647 * Perform case-insensitive match against a list of file extensions.
648 * Returns true if the extension is in the list.
649 *
650 * @param string $ext
651 * @param array $list
652 * @return bool
653 */
654 function checkFileExtension( $ext, $list ) {
655 return in_array( strtolower( $ext ), $list );
656 }
657
658 /**
659 * Perform case-insensitive match against a list of file extensions.
660 * Returns true if any of the extensions are in the list.
661 *
662 * @param array $ext
663 * @param array $list
664 * @return bool
665 */
666 function checkFileExtensionList( $ext, $list ) {
667 foreach( $ext as $e ) {
668 if( in_array( strtolower( $e ), $list ) ) {
669 return true;
670 }
671 }
672 return false;
673 }
674
675 /**
676 * Verifies that it's ok to include the uploaded file
677 *
678 * @param string $tmpfile the full path of the temporary file to verify
679 * @param string $extension The filename extension that the file is to be served with
680 * @return mixed true of the file is verified, a WikiError object otherwise.
681 */
682 function verify( $tmpfile, $extension ) {
683 #magically determine mime type
684 $magic=& wfGetMimeMagic();
685 $mime= $magic->guessMimeType($tmpfile,false);
686
687 $fname= "SpecialUpload::verify";
688
689 #check mime type, if desired
690 global $wgVerifyMimeType;
691 if ($wgVerifyMimeType) {
692
693 #check mime type against file extension
694 if( !$this->verifyExtension( $mime, $extension ) ) {
695 return new WikiErrorMsg( 'uploadcorrupt' );
696 }
697
698 #check mime type blacklist
699 global $wgMimeTypeBlacklist;
700 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
701 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
702 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
703 }
704 }
705
706 #check for htmlish code and javascript
707 if( $this->detectScript ( $tmpfile, $mime ) ) {
708 return new WikiErrorMsg( 'uploadscripted' );
709 }
710
711 /**
712 * Scan the uploaded file for viruses
713 */
714 $virus= $this->detectVirus($tmpfile);
715 if ( $virus ) {
716 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
717 }
718
719 wfDebug( "$fname: all clear; passing.\n" );
720 return true;
721 }
722
723 /**
724 * Checks if the mime type of the uploaded file matches the file extension.
725 *
726 * @param string $mime the mime type of the uploaded file
727 * @param string $extension The filename extension that the file is to be served with
728 * @return bool
729 */
730 function verifyExtension( $mime, $extension ) {
731 $fname = 'SpecialUpload::verifyExtension';
732
733 if (!$mime || $mime=="unknown" || $mime=="unknown/unknown") {
734 wfDebug( "$fname: passing file with unknown mime type\n" );
735 return true;
736 }
737
738 $magic=& wfGetMimeMagic();
739
740 $match= $magic->isMatchingExtension($extension,$mime);
741
742 if ($match===NULL) {
743 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
744 return true;
745 } elseif ($match===true) {
746 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
747
748 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
749 return true;
750
751 } else {
752 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
753 return false;
754 }
755 }
756
757 /** Heuristig for detecting files that *could* contain JavaScript instructions or
758 * things that may look like HTML to a browser and are thus
759 * potentially harmful. The present implementation will produce false positives in some situations.
760 *
761 * @param string $file Pathname to the temporary upload file
762 * @param string $mime The mime type of the file
763 * @return bool true if the file contains something looking like embedded scripts
764 */
765 function detectScript($file,$mime) {
766
767 #ugly hack: for text files, always look at the entire file.
768 #For binarie field, just check the first K.
769
770 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
771 else {
772 $fp = fopen( $file, 'rb' );
773 $chunk = fread( $fp, 1024 );
774 fclose( $fp );
775 }
776
777 $chunk= strtolower( $chunk );
778
779 if (!$chunk) return false;
780
781 #decode from UTF-16 if needed (could be used for obfuscation).
782 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
783 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
784 else $enc= NULL;
785
786 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
787
788 $chunk= trim($chunk);
789
790 #FIXME: convert from UTF-16 if necessarry!
791
792 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
793
794 #check for HTML doctype
795 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
796
797 /**
798 * Internet Explorer for Windows performs some really stupid file type
799 * autodetection which can cause it to interpret valid image files as HTML
800 * and potentially execute JavaScript, creating a cross-site scripting
801 * attack vectors.
802 *
803 * Apple's Safari browser also performs some unsafe file type autodetection
804 * which can cause legitimate files to be interpreted as HTML if the
805 * web server is not correctly configured to send the right content-type
806 * (or if you're really uploading plain text and octet streams!)
807 *
808 * Returns true if IE is likely to mistake the given file for HTML.
809 * Also returns true if Safari would mistake the given file for HTML
810 * when served with a generic content-type.
811 */
812
813 $tags = array(
814 '<body',
815 '<head',
816 '<html', #also in safari
817 '<img',
818 '<pre',
819 '<script', #also in safari
820 '<table',
821 '<title' #also in safari
822 );
823
824 foreach( $tags as $tag ) {
825 if( false !== strpos( $chunk, $tag ) ) {
826 return true;
827 }
828 }
829
830 /*
831 * look for javascript
832 */
833
834 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
835 $chunk = Sanitizer::decodeCharReferences( $chunk );
836
837 #look for script-types
838 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
839
840 #look for html-style script-urls
841 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
842
843 #look for css-style script-urls
844 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
845
846 wfDebug("SpecialUpload::detectScript: no scripts found\n");
847 return false;
848 }
849
850 /** Generic wrapper function for a virus scanner program.
851 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
852 * $wgAntivirusRequired may be used to deny upload if the scan fails.
853 *
854 * @param string $file Pathname to the temporary upload file
855 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
856 * or a string containing feedback from the virus scanner if a virus was found.
857 * If textual feedback is missing but a virus was found, this function returns true.
858 */
859 function detectVirus($file) {
860 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
861
862 $fname= "SpecialUpload::detectVirus";
863
864 if (!$wgAntivirus) { #disabled?
865 wfDebug("$fname: virus scanner disabled\n");
866
867 return NULL;
868 }
869
870 if (!$wgAntivirusSetup[$wgAntivirus]) {
871 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
872
873 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
874
875 return "unknown antivirus: $wgAntivirus";
876 }
877
878 #look up scanner configuration
879 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
880 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
881 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
882
883 $scanner= $virus_scanner; #copy, so we can resolve the pattern
884
885 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
886 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
887
888 wfDebug("$fname: running virus scan: $scanner \n");
889
890 #execute virus scanner
891 $code= false;
892
893 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
894 # that does not seem to be worth the pain.
895 # Ask me (Duesentrieb) about it if it's ever needed.
896 if (wfIsWindows()) exec("$scanner",$output,$code);
897 else exec("$scanner 2>&1",$output,$code);
898
899 $exit_code= $code; #remeber for user feedback
900
901 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
902 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
903 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
904 }
905
906 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
907 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
908
909 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
910 else return NULL;
911 }
912 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
913 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
914 return NULL;
915 }
916 else if ($code===AV_NO_VIRUS) {
917 wfDebug("$fname: file passed virus scan.\n");
918 return false; #no virus found
919 }
920 else {
921 $output= join("\n",$output);
922 $output= trim($output);
923
924 if (!$output) $output= true; #if ther's no output, return true
925 else if ($msg_pattern) {
926 $groups= array();
927 if (preg_match($msg_pattern,$output,$groups)) {
928 if ($groups[1]) $output= $groups[1];
929 }
930 }
931
932 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
933 return $output;
934 }
935 }
936
937 /**
938 * Check if the temporary file is MacBinary-encoded, as some uploads
939 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
940 * If so, the data fork will be extracted to a second temporary file,
941 * which will then be checked for validity and either kept or discarded.
942 *
943 * @access private
944 */
945 function checkMacBinary() {
946 $macbin = new MacBinary( $this->mUploadTempName );
947 if( $macbin->isValid() ) {
948 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
949 $dataHandle = fopen( $dataFile, 'wb' );
950
951 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
952 $macbin->extractData( $dataHandle );
953
954 $this->mUploadTempName = $dataFile;
955 $this->mUploadSize = $macbin->dataForkLength();
956
957 // We'll have to manually remove the new file if it's not kept.
958 $this->mRemoveTempFile = true;
959 }
960 $macbin->close();
961 }
962
963 /**
964 * If we've modified the upload file we need to manually remove it
965 * on exit to clean up.
966 * @access private
967 */
968 function cleanupTempFile() {
969 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
970 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
971 unlink( $this->mUploadTempName );
972 }
973 }
974
975 /**
976 * Check if there's an overwrite conflict and, if so, if restrictions
977 * forbid this user from performing the upload.
978 *
979 * @return mixed true on success, WikiError on failure
980 * @access private
981 */
982 function checkOverwrite( $name ) {
983 $img = Image::newFromName( $name );
984 if( is_null( $img ) ) {
985 // Uh... this shouldn't happen ;)
986 // But if it does, fall through to previous behavior
987 return false;
988 }
989
990 $error = '';
991 if( $img->exists() ) {
992 global $wgUser, $wgOut;
993 if( $img->isLocal() ) {
994 if( !$wgUser->isAllowed( 'reupload' ) ) {
995 $error = 'fileexists-forbidden';
996 }
997 } else {
998 if( !$wgUser->isAllowed( 'reupload' ) ||
999 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1000 $error = "fileexists-shared-forbidden";
1001 }
1002 }
1003 }
1004
1005 if( $error ) {
1006 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1007 return new WikiError( $wgOut->parse( $errorText ) );
1008 }
1009
1010 // Rockin', go ahead and upload
1011 return true;
1012 }
1013
1014 }
1015 ?>